package com.cn.shuangzi;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.PersistableBundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.app.hubert.guide.NewbieGuide;
import com.app.hubert.guide.core.Builder;
import com.app.hubert.guide.model.GuidePage;
import com.app.hubert.guide.model.HighLight;
import com.app.hubert.guide.model.RelativeGuide;
import com.cn.shuangzi.common.PermissionDescAlertListener;
import com.cn.shuangzi.common.SZConst;
import com.cn.shuangzi.permission.RequestExternalStorageManagePermissionHelper;
import com.cn.shuangzi.permission.RequestPermissionHelper;
import com.cn.shuangzi.retrofit.SZRetrofitManager;
import com.cn.shuangzi.retrofit.SZRetrofitResponseListener;
import com.cn.shuangzi.util.SZGlide;
import com.cn.shuangzi.util.SZUtil;
import com.cn.shuangzi.util.SZValidatorUtil;
import com.cn.shuangzi.view.AlertWidget;
import com.cn.shuangzi.view.pop.BottomCtrlPop;
import com.cn.shuangzi.view.pop.FilterPop;
import com.cn.shuangzi.view.pop.common.CtrlItem;
import com.cn.shuangzi.view.sweet_alert.SweetAlertDialog;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import io.reactivex.Observable;


/**
 * AppCompatActivity基类
 * Created by CN on 2016/10/31.
 */
public abstract class SZBaseActivity extends AppCompatActivity {
    private Toolbar toolBar;
    private ImageButton imgLeft;
    private ImageButton imgRight;
    private TextView txtTitle;
    private TextView txtTitleRight;
    private TextView txtTitleLeft;
    private FrameLayout fltContent;
    public View viewChildContent;
    private View includeToolbar;
    private AlertWidget bar;
    public View viewNetError;
    public View viewEmpty;
    public View viewLogin;
    public View rltBase;
    public View titleCutLine;
    private boolean isCanPerformErrorClick;
    private BottomCtrlPop bottomCtrlPop;
    private boolean isPrepared = false;
    private boolean isRegist = false;
    private boolean isTransparentStatus = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SZApp.getInstance().addActivity(this);
        setContentView(R.layout.activity_base);
        if (isShowDarkTitleText()) {
            setDarkTitleText();
        }
        bindViews();
        if (isShowTitleInit()) {
            toolBar.setVisibility(View.VISIBLE);
        } else {
            toolBar.setVisibility(View.GONE);
        }
        preLoadChildView();
        fltContent.postDelayed(new Runnable() {
            @Override
            public void run() {
                addChildContentView(onGetChildView());
            }
        }, getDelayTimeOnLoadChildView());
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            if (isShowDarkTitleText()) {
                setDarkTitleText();
            }
        }
    }

    private void bindViews() {
        includeToolbar = findViewById(R.id.includeToolbar);
        toolBar = includeToolbar.findViewById(R.id.toolBar);
        titleCutLine = includeToolbar.findViewById(R.id.titleCutLine);
        imgLeft = includeToolbar.findViewById(R.id.imgLeft);
        imgRight = includeToolbar.findViewById(R.id.imgRight);
        txtTitle = includeToolbar.findViewById(R.id.txtTitle);
        txtTitleRight = includeToolbar.findViewById(R.id.txtTitleRight);
        txtTitleLeft = includeToolbar.findViewById(R.id.txtTitleLeft);
        fltContent = findViewById(R.id.fltContent);
        rltBase = findViewById(R.id.rltBase);
        viewNetError = findViewById(R.id.viewNetError);

        isCanPerformErrorClick = true;
        viewNetError.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isCanPerformErrorClick) {
                    isShowError(false);
                    onReloadData(false);
                }
            }
        });
        viewEmpty = findViewById(R.id.viewEmpty);
        viewLogin = findViewById(R.id.viewLogin);
        viewLogin.findViewById(R.id.btnLogin).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onLoginBtnClick();
            }
        });
    }

    /**
     * 添加子contentView
     *
     * @param resId
     */
    private void addChildContentView(int resId) {
        if (resId == 0)
            return;
        viewChildContent = LayoutInflater.from(this).inflate(resId, null);
        fltContent.addView(viewChildContent);
        onBindChildViews();
        onBindChildListeners();
        fltContent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (fltContent.getWidth() > 0) {
                    fltContent.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    onChildViewCreated();
                    isPrepared = true;
                }
            }
        });
    }

    public void preLoadChildView() {
    }

    /**
     * 获取子view的layout
     *
     * @return
     */
    protected abstract int onGetChildView();

    /**
     * 初始化绑定view控件
     */
    protected abstract void onBindChildViews();

    /**
     * 初始化绑定监听事件
     */
    protected abstract void onBindChildListeners();

    /**
     * 子view创建
     */
    protected abstract void onChildViewCreated();

    /**
     * ******************
     * 点击error界面重新加载数据
     * ******************
     */
    protected abstract void onReloadData(boolean isRefresh);

    /**
     * ******************
     * 点击登录按钮
     * ******************
     */
    public void onLoginBtnClick() {
    }

    /**
     * 子view的延迟加载时间
     *
     * @return
     */
    protected long getDelayTimeOnLoadChildView() {
        return 0;
    }


    /**
     * 判断是否登录
     *
     * @param isOpenLogin 是否需要打开登录页
     * @return
     */
    public boolean isLogin(boolean isOpenLogin) {
        return false;
    }

    /**
     * 设置标题
     *
     * @param resId
     */
    public void setTitleTxt(int resId) {
        setTitleTxt(getString(resId));
    }

    /**
     * 设置标题
     *
     * @param title
     */
    public void setTitleTxt(String title) {
        txtTitle.setText(title);
    }

    /**
     * 设置标题字体颜色
     *
     * @param colors
     */
    public void setTitleTxtColor(int colors) {
        txtTitle.setTextColor(getResources().getColor(colors));
    }

    public void setWhiteStatusBarDarkText() {
        if (android.os.Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
            setStatusBarColor(android.R.color.white);
            setStatusBarTextColorStyleBelowBar(true);
        } else {
            setStatusBarColor(R.color.colorStatusBar);
        }
    }

    public void setStatusBarTextColorStyle(boolean dark) {
        try {
            View decor = getWindow().getDecorView();
            if (decor != null) {
                if (dark) {
                    decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
                } else {
                    decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setStatusBarTextColorStyleBelowBar(boolean dark) {
        try {
            View decor = getWindow().getDecorView();
            if (decor != null) {
                if (dark) {
                    decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
                } else {
                    decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setDarkStatusText() {
        setStatusBarTextColorStyle(true);
    }

    public void setWhiteStatusText() {
        setStatusBarTextColorStyle(false);
    }

    public void setDarkTitleText() {
        setStatusBarTextColorStyle(true);
    }

    /**
     * 设置标题背景颜色
     *
     * @param colors
     */
    public void setToolBarColor(int colors) {
        toolBar.setBackgroundColor(colors);
    }

    public TextView getMyTitle() {
        return this.txtTitle;
    }

    public void isShowTitle(final boolean isShow) {
        includeToolbar.post(new Runnable() {
            @Override
            public void run() {
                if (isShow) {
                    includeToolbar.setVisibility(View.VISIBLE);
                } else {
                    includeToolbar.setVisibility(View.GONE);
                }
            }
        });
    }

    public void isShowTitleCutLine(boolean isShow) {
        titleCutLine.setVisibility(isShow ? View.VISIBLE : View.GONE);
    }

    public void showBackImgLeft(int backResId) {
        setImgLeftBg(backResId);
        imgLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackBtnPressed();
                finish();
            }
        });
    }

    public void onBackBtnPressed() {
    }

    /**
     * 获取标题左侧imgBtn
     *
     * @return
     */
    public ImageButton getImgLeft() {
        return this.imgLeft;
    }

    public void isShowImgLeft(boolean isShow) {
        if (isShow) {
            imgLeft.setVisibility(View.VISIBLE);
        } else {
            imgLeft.setVisibility(View.GONE);
        }
    }

    public void setImgLeftBg(int resId) {
        this.imgLeft.setImageResource(resId);
        isShowImgLeft(true);
    }

    public void setImgLeftBg(int resId, View.OnClickListener onClickListener) {
        this.imgLeft.setImageResource(resId);
        this.imgLeft.setOnClickListener(onClickListener);
        isShowImgLeft(true);
    }

    /**
     * 获取右侧imgBtn
     *
     * @return
     */
    public ImageButton getImgRight() {
        return this.imgRight;
    }

    public void isShowImgRight(boolean isShow) {
        if (isShow) {
            imgRight.setVisibility(View.VISIBLE);
        } else {
            imgRight.setVisibility(View.GONE);
        }
    }

    public void setTxtTitleRight(int resId) {
        setTxtTitleRight(getString(resId));
    }

    public void setTxtTitleRight(int resId, View.OnClickListener onClickListener) {
        setTxtTitleRight(getString(resId));
        txtTitleRight.setOnClickListener(onClickListener);
    }

    public void setTxtTitleRight(String titleRight) {
        txtTitleRight.setText(titleRight);
        isShowTxtRight(true);
    }

    public void setTxtTitleRight(String titleRight, View.OnClickListener onClickListener) {
        txtTitleRight.setText(titleRight);
        txtTitleRight.setOnClickListener(onClickListener);
        isShowTxtRight(true);
    }

    public TextView getTxtTitleRight() {
        return txtTitleRight;
    }

    public void isShowTxtRight(boolean isShow) {
        if (isShow) {
            txtTitleRight.setVisibility(View.VISIBLE);
        } else {
            txtTitleRight.setVisibility(View.GONE);
        }
    }

    public void setTxtTitleLeft(int resId) {
        setTxtTitleLeft(getString(resId));
    }

    public void setTxtTitleLeft(int resId, View.OnClickListener onClickListener) {
        setTxtTitleLeft(getString(resId));
        txtTitleLeft.setOnClickListener(onClickListener);
    }

    public void setTxtTitleLeft(String titleLeft) {
        txtTitleLeft.setText(titleLeft);
        isShowTxtLeft(true);
    }

    public void setTxtTitleLeft(String titleLeft, View.OnClickListener onClickListener) {
        txtTitleLeft.setText(titleLeft);
        txtTitleLeft.setOnClickListener(onClickListener);
        isShowTxtLeft(true);
    }

    public TextView getTxtTitleLeft() {
        return txtTitleLeft;
    }

    public void isShowTxtLeft(boolean isShow) {
        if (isShow) {
            txtTitleLeft.setVisibility(View.VISIBLE);
        } else {
            txtTitleLeft.setVisibility(View.GONE);
        }
    }

    public void setImgRightBg(int resId) {
        this.imgRight.setImageResource(resId);
        isShowImgRight(true);
    }

    public void setImgRightBg(int resId, View.OnClickListener onClickListener) {
        this.imgRight.setImageResource(resId);
        this.imgRight.setOnClickListener(onClickListener);
        isShowImgRight(true);
    }

    public View getBaseView() {
        return this.rltBase;
    }

    /**
     * 获取toolBar
     *
     * @return
     */
    public Toolbar getToolBar() {
        return this.toolBar;
    }

    /**
     * 获取状态栏的高度
     *
     * @return
     */

    public int getStatusBarHeight() {
        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    public void setTransparentStatusBarWhiteText() {
        setStatusBarTrans();
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
            setStatusBarTextColorStyle(false);
        }
    }

    /**
     * 状态栏透明
     */
    public void setStatusBarTrans() {
        isTransparentStatus = true;
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//21表示5.0
                Window window = getWindow();
                if (window.getDecorView() != null) {
                    window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                    window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                    window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                    window.setStatusBarColor(Color.TRANSPARENT);
                }
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//19表示4.4
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                //虚拟键盘也透明
                //getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setStatusBarColor(int colorResId) {
        isTransparentStatus = false;
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//                getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                getWindow().setStatusBarColor(getResources().getColor(colorResId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setStatusBarColor(String color) {
        isTransparentStatus = false;
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                getWindow().setStatusBarColor(Color.parseColor(color));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void hideNavigationBar() {
        if (getWindow().getDecorView() != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                //       设置屏幕始终在前面，不然点击鼠标，重新出现虚拟按键
                getWindow().getDecorView().setSystemUiVisibility(
                        View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav
                                // bar
                                | View.SYSTEM_UI_FLAG_IMMERSIVE);
            } else {
                getWindow().getDecorView().setSystemUiVisibility(
                        View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav
                );
            }
        }
    }

    public int getNavigationBarHeight() {
        int height = 0;
        try {
            int resourceId = getResources().getIdentifier("navigation_bar_height", "dimen", "android");
            height = getResources().getDimensionPixelSize(resourceId);
        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
        }
        return height;
    }

    public <T extends Serializable> T getSerializableExtra() {
        return (T) getIntent().getSerializableExtra(getRequestTag());
    }

    public String getStringExtra() {
        return getIntent().getStringExtra(getRequestTag());
    }

    public <T extends Serializable> T getSerializableExtra(String tag) {
        return (T) getIntent().getSerializableExtra(tag);
    }

    public String getStringExtra(String tag) {
        return getIntent().getStringExtra(tag);
    }

    public void startActivity(Serializable data, Class to) {
        startActivity(data, to.getSimpleName(), to);
    }

    public void startActivity(Serializable data, String tag, Class to) {
        Intent intent = new Intent(this, to);
        intent.putExtra(tag, data);
        startActivity(intent);
    }

    public void startActivity(Serializable data, Class to, boolean isFinish) {
        if (isFinish) {
            SZApp.getInstance().removeActivity(this);
        }
        Intent intent = new Intent(this, to);
        intent.putExtra(to.getSimpleName(), data);
        startActivity(intent);
        if (isFinish) {
            finish();
        }
    }

    public void startActivity(String data, Class to) {
        startActivity(data, to.getSimpleName(), to);
    }

    public void startActivity(String data, String tag, Class to) {
        Intent intent = new Intent(this, to);
        intent.putExtra(tag, data);
        startActivity(intent);
    }

    public void startActivity(String data, Class to, boolean isFinish) {
        if (isFinish) {
            SZApp.getInstance().removeActivity(this);
        }
        Intent intent = new Intent(this, to);
        intent.putExtra(to.getSimpleName(), data);
        startActivity(intent);
        if (isFinish) {
            finish();
        }
    }

    public SZBaseActivity getActivity() {
        return this;
    }

    /**
     * 启动activity
     *
     * @param tClass
     * @param isFinish 是否关闭本界面
     */
    public void startActivity(Class<?> tClass, Bundle extras, boolean isFinish) {
        if (isFinish) {
            SZApp.getInstance().removeActivity(this);
        }
        Intent intent = new Intent(this, tClass);
        if (extras != null) {
            intent.putExtras(extras);
        }
        startActivity(intent);
        if (isFinish) {
            finish();
        }
    }

    /**
     * 启动activity
     *
     * @param tClass
     */
    public void startActivity(Class<?> tClass) {
        startActivity(tClass, (Bundle) null, false);
    }

    /**
     * 启动activity
     *
     * @param tClass
     * @param isFinish 是否关闭本界面
     */
    public void startActivity(Class<?> tClass, boolean isFinish) {
        startActivity(tClass, (Bundle) null, isFinish);
    }

    /**
     * 获取网络请求的tag
     *
     * @return
     */
    public String getRequestTag() {
        return this.getClass().getSimpleName();
    }

    /**
     * 通过tag撤销请求
     */
    public void cancelByTag(String tag) {
        if (tag == null)
            return;
        SZRetrofitManager.getInstance().cancelDisposable(tag);
    }

    public void isShowContent(boolean isShow) {
        if (bar != null)
            bar.close();
        if (isShow) {
            fltContent.setVisibility(View.VISIBLE);
            isShowError(false);
            isShowEmpty(false);
            isShowLogin(false);
        } else {
            fltContent.setVisibility(View.GONE);
        }
    }

    public void showError(int imgErrorRes, int txtErrorRes) {
        showError(imgErrorRes, getString(txtErrorRes));
    }

    public void showError(int imgErrorRes, String txtError) {
        closeBar();
        isCanPerformErrorClick = false;
        viewNetError.setVisibility(View.VISIBLE);
        isShowContent(false);
        isShowEmpty(false);
        isShowLogin(false);
        try {
            if (txtError != null) {
                ((TextView) viewNetError.findViewById(R.id.txtHintTop)).setText(txtError);
            }
            if (imgErrorRes != 0) {
                ((ImageView) viewNetError.findViewById(R.id.imgNetError)).setImageResource(imgErrorRes);
            } else {
                ((ImageView) viewNetError.findViewById(R.id.imgNetError)).setImageResource(R.mipmap.ic_data_error);
            }
            viewNetError.findViewById(R.id.txtHintBottom).setVisibility(View.GONE);
        } catch (Exception e) {
        }
    }

    public void showErrorWithMsg(int errorResId, int errorId, String errorMsg) {
        if (errorId == SZRetrofitManager.ERROR_NET_FAILED) {
            isShowError(true);
        } else {
            if (errorId == SZRetrofitManager.ERROR_EXCEPTION || TextUtils.isEmpty(errorMsg)) {
                showError(errorResId, R.string.txt_service_error);
            } else {
                showError(errorResId, errorMsg);
            }
        }
    }

    public void showErrorWithMsg(int errorId, String errorMsg) {
        showErrorWithMsg(SZApp.getInstance().getServiceErrorImgResId(), errorId, errorMsg);
    }

    public void isShowError(boolean isShow) {
        if (bar != null)
            bar.close();
        if (isShow) {
            isCanPerformErrorClick = true;
            try {
                ((TextView) viewNetError.findViewById(R.id.txtHintTop)).setText(getString(R.string.txt_net_error_hint_top));
                ((TextView) viewNetError.findViewById(R.id.txtHintBottom)).setText(getString(R.string.txt_net_error_hint_bottom));
                viewNetError.findViewById(R.id.txtHintBottom).setVisibility(View.VISIBLE);
            } catch (Exception e) {
            }

            ((ImageView) viewNetError.findViewById(R.id.imgNetError)).setImageResource(R.mipmap.ic_error);
            viewNetError.setVisibility(View.VISIBLE);
            isShowContent(false);
            isShowEmpty(false);
            isShowLogin(false);
        } else {
            viewNetError.setVisibility(View.GONE);
        }
    }

    public void isShowEmpty(boolean isShow) {
        if (bar != null)
            bar.close();
        if (isShow) {
            viewEmpty.setVisibility(View.VISIBLE);
            isShowContent(false);
            isShowError(false);
            isShowLogin(false);
        } else {
            viewEmpty.setVisibility(View.GONE);
        }
    }

    public void isShowLogin(boolean isShow) {
        if (bar != null)
            bar.close();
        if (isShow) {
            viewLogin.setVisibility(View.VISIBLE);
            isShowContent(false);
            isShowError(false);
            isShowEmpty(false);
        } else {
            viewLogin.setVisibility(View.GONE);
        }
    }

    public void setEmptyImg(int resId) {
        ((ImageView) viewEmpty.findViewById(R.id.imgEmpty)).setImageResource(resId);
    }

    public void setEmptyTxt(int resId) {
        ((TextView) viewEmpty.findViewById(R.id.txtEmpty)).setText(resId);
    }

    public void showBar() {
        showBar(false, false);
    }

    public void showBarTransparentStyle() {
        showBar(false, true);
    }

    public void showBar(boolean cancelable) {
        showBar(cancelable, false);
    }

    public void showBar(boolean cancelable, boolean isTransparentStyle) {
        closeBar();
        bar = new AlertWidget(getActivity(), isTransparentStyle);
        bar.setCancelable(cancelable);
        bar.setCanceledOnTouchOutside(cancelable);
        bar.showBar();
    }

    public void closeBar() {
        if (bar != null) {
            bar.close();
        }
    }

    public void setPaddingStatusBarTrans() {
        rltBase.setPadding(0, getStatusBarHeight(), 0, 0);
    }

    /**
     * 是否已经加载准备完成
     *
     * @return
     */
    public boolean isPrepared() {
        return isPrepared;
    }

    /**
     * AndroidR 外部文件管理
     *
     * @param requestExternalStorageManagePermissionHelper
     */

    private RequestExternalStorageManagePermissionHelper requestExternalStorageManagePermissionHelper;

    public void setRequestExternalStorageManagePermissionHelper(RequestExternalStorageManagePermissionHelper requestExternalStorageManagePermissionHelper) {
        this.requestExternalStorageManagePermissionHelper = requestExternalStorageManagePermissionHelper;
    }

    public void requestExternalStorageManagerPermission(RequestExternalStorageManagePermissionHelper requestExternalStorageManagePermissionHelper) {
        setRequestExternalStorageManagePermissionHelper(requestExternalStorageManagePermissionHelper);
        this.requestExternalStorageManagePermissionHelper.checkPermission();
    }

    private RequestPermissionHelper requestPermissionHelper;

    /**
     * 设置权限管理类
     *
     * @param requestPermissionHelper
     */

    public void requestPermissionWithoutDesc(RequestPermissionHelper requestPermissionHelper) {
        this.requestPermissionWithoutDesc(requestPermissionHelper, true);
    }

    public void requestPermissionWithoutDesc(RequestPermissionHelper requestPermissionHelper, boolean isRemoveRequestPermissionViewP) {
        this.requestPermissionHelper = requestPermissionHelper;
        this.requestPermissionHelper.setRemoveRequestPermissionViewP(isRemoveRequestPermissionViewP);
        this.requestPermissionHelper.checkPermissions();
    }

    public void requestPermission(String permissionDesc, RequestPermissionHelper requestPermissionHelper) {
        this.requestPermission(permissionDesc, null, requestPermissionHelper);
    }

    public void requestPermission(String permissionDesc, PermissionDescAlertListener permissionDescAlertListener, RequestPermissionHelper requestPermissionHelper) {
        this.requestPermission(permissionDesc, permissionDescAlertListener, requestPermissionHelper, true);
    }

    public void requestPermission(String permissionDesc, final PermissionDescAlertListener permissionDescAlertListener, final RequestPermissionHelper requestPermissionHelper, final boolean isRemoveRequestPermissionViewP) {
        if (requestPermissionHelper.hasPermission()) {
            this.requestPermissionHelper = requestPermissionHelper;
            this.requestPermissionHelper.setRemoveRequestPermissionViewP(isRemoveRequestPermissionViewP);
            this.requestPermissionHelper.checkPermissions();
            return;
        }
        showAlert(SweetAlertDialog.NORMAL_TYPE, "权限申请说明", permissionDesc, "去申请", new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                sweetAlertDialog.dismissWithAnimation();
                SZBaseActivity.this.requestPermissionHelper = requestPermissionHelper;
                SZBaseActivity.this.requestPermissionHelper.setRemoveRequestPermissionViewP(isRemoveRequestPermissionViewP);
                SZBaseActivity.this.requestPermissionHelper.checkPermissions();
            }
        }, "取消", new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                sweetAlertDialog.dismissWithAnimation();
                if (permissionDescAlertListener != null) {
                    permissionDescAlertListener.onCancel();
                }
            }
        }, true).setCancelable(false);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestPermissionHelper != null) {
            requestPermissionHelper.onActivityResult(requestCode, resultCode, data);
        }
        if (requestExternalStorageManagePermissionHelper != null) {
            requestExternalStorageManagePermissionHelper.onActivityResult(requestCode);
            requestExternalStorageManagePermissionHelper = null;
        }
    }

    public void removeRequestPermissionHelper() {
        requestPermissionHelper = null;
    }

    public void removeRequestExternalStorageManagePermissionHelper() {
        requestExternalStorageManagePermissionHelper = null;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[]
            grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestPermissionHelper != null) {
            requestPermissionHelper.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    public void request(Observable observable, SZRetrofitResponseListener retrofitResponseListener) {
        SZRetrofitManager.getInstance().request(observable, getRequestTag(), retrofitResponseListener);
    }

    public void showBottomCtrl(List<CtrlItem> ctrlItemList, FilterPop.OnItemClickListener onItemClickListener) {
        showBottomCtrl(ctrlItemList, onItemClickListener, null, false);
    }

    public void showBottomCtrl(List<CtrlItem> ctrlItemList, FilterPop.OnItemClickListener onItemClickListener, String title, boolean isReset) {
        if (bottomCtrlPop == null || isReset) {
            bottomCtrlPop = new BottomCtrlPop(this, ctrlItemList, onItemClickListener, title);
        }
        bottomCtrlPop.showOnAnchorFromBottom(getBaseView());
    }

    public void showBottomCtrl(List<CtrlItem> ctrlItemList, FilterPop.OnItemClickListener onItemClickListener, String title, boolean isReset, boolean isCheckMode) {
        if (bottomCtrlPop == null || isReset) {
            bottomCtrlPop = new BottomCtrlPop(this, ctrlItemList, onItemClickListener, isCheckMode, title);
        }
        bottomCtrlPop.showOnAnchorFromBottom(getBaseView());
    }

    public SweetAlertDialog showBuyVipAlert(final Class buyVipClass) {
        SZManager.getInstance().onUMEvent(SZConst.EVENT_VIP_SHOW_OTHER);
        return showWarningAlert("您还不是尊贵VIP用户", "是否前去购买？", new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                sweetAlertDialog.dismissWithAnimation();
                startActivity(buyVipClass);
                SZManager.getInstance().onUMEvent(SZConst.EVENT_VIP_CLICK_OTHER);
            }
        });
    }

    //通过上传图片功能提示的会员购买
    public SweetAlertDialog showBuyVipAlertImg(final Class buyVipClass) {
        SZManager.getInstance().onUMEvent(SZConst.EVENT_VIP_SHOW_IMG_ADD);
        return showWarningAlert("您还不是尊贵VIP用户", "是否前去购买？", new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                sweetAlertDialog.dismissWithAnimation();
                startActivity(buyVipClass);
                SZManager.getInstance().onUMEvent(SZConst.EVENT_VIP_CLICK_IMG_ADD);
            }
        });
    }

    public SweetAlertDialog showSuccessAlert(String title, String content) {
        return showAlert(SweetAlertDialog.SUCCESS_TYPE, title, content, null, null, null, null, false);
    }

    public SweetAlertDialog showSuccessAlert(String title, String content, String okText, SweetAlertDialog.OnSweetClickListener onClickListener) {
        return showAlert(SweetAlertDialog.SUCCESS_TYPE, title, content, okText, onClickListener, null, null, false);
    }

    public SweetAlertDialog showAlert(int type, String title, String content, String okText, SweetAlertDialog.OnSweetClickListener onClickListener) {
        return showAlert(type, title, content, okText, onClickListener, null, null, false);
    }

    public SweetAlertDialog showWarningAlert(String title, String content, SweetAlertDialog.OnSweetClickListener onOkClickListener) {
        return showWarningAlert(title, content, null, null, onOkClickListener);
    }

    public SweetAlertDialog showWarningAlertCountdown(String title, String content) {
        return showWarningAlertCountdown(title, content, null, 5, null, null);
    }

    public SweetAlertDialog showWarningAlertCountdown(String title, String content, boolean isShowCloseBtn) {
        return showWarningAlertCountdown(title, content, null, 5, null, null, null, null, isShowCloseBtn);
    }

    public SweetAlertDialog showWarningAlertCountdown(String title, String content, String countdownText, final int seconds, String okText, SweetAlertDialog.OnSweetClickListener onOkClickListener) {
        return showWarningAlertCountdown(title, content, countdownText, seconds, okText, onOkClickListener, null, null, false);
    }

    public SweetAlertDialog showWarningAlertCountdown(String title, String content, String countdownText, final int seconds, String okText, SweetAlertDialog.OnSweetClickListener onOkClickListener
            , final String cancelText, final SweetAlertDialog.OnSweetClickListener onCancelClickListener, final boolean isShowCloseBtn) {
        if (countdownText == null) {
            countdownText = "请阅读";
        }
        final String finalCountdownText = countdownText;

        if (okText == null) {
            okText = "确定";
        }
        final String finalOkText = okText;

        final SweetAlertDialog sweetAlertDialog = showWarningAlert(title, content, onOkClickListener);
        sweetAlertDialog.setCancelable(false);
        sweetAlertDialog.showCancelButton(false);
        final Button button = sweetAlertDialog.findViewById(R.id.confirm_button);
        for (int i = 1; i <= seconds; i++) {
            final int finalI = i;
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (seconds - finalI > 0) {
                        sweetAlertDialog.setConfirmText(finalCountdownText + "（" + (seconds - finalI) + "）");
                    } else {
                        button.setEnabled(true);
                        button.setBackgroundResource(R.drawable.blue_button_background);
                        sweetAlertDialog.setConfirmText(finalOkText);
                        if (onCancelClickListener != null) {
                            sweetAlertDialog.setCancelClickListener(onCancelClickListener);
                            if (cancelText != null) {
                                sweetAlertDialog.setCancelText(cancelText);
                            }
                            sweetAlertDialog.showCancelButton(true);
                        }
                        sweetAlertDialog.showCloseButton(isShowCloseBtn);
                    }
                }
            }, i * 1000);
        }
        button.setBackgroundResource(R.drawable.gray_button_background);
        sweetAlertDialog.setConfirmText(finalCountdownText + "（" + seconds + "）");
        button.setEnabled(false);
        return sweetAlertDialog;
    }

    public SweetAlertDialog showWarningAlert(String title, String content, String okText, String cancelText, SweetAlertDialog.OnSweetClickListener onOkClickListener) {
        return showAlert(SweetAlertDialog.WARNING_TYPE, title, content, okText, onOkClickListener, cancelText, null, true);
    }

    public SweetAlertDialog showErrorAlert(String title, String content, String okText) {
        return showAlert(SweetAlertDialog.ERROR_TYPE, title, content, okText, null, null, null, false);
    }

    public SweetAlertDialog showNormalAlert(String title, String content, String okText) {
        return showAlert(SweetAlertDialog.NORMAL_TYPE, title, content, okText, null, null, null, false);
    }

    public SweetAlertDialog showAlert(int type, String title, String content, String okText, SweetAlertDialog.OnSweetClickListener onOkClickListener,
                                      String cancelText, SweetAlertDialog.OnSweetClickListener onCancelClickListener, boolean isShowCancelButton) {
        SweetAlertDialog sweetAlertDialog = new SweetAlertDialog(this, type)
                .setTitleText(title != null ? title : getString(R.string.dialog_default_title))
                .setContentText(content)
                .setCancelText(isShowCancelButton ? cancelText != null ? cancelText : getString(R.string.dialog_cancel) : null)
                .setConfirmText(okText != null ? okText : getString(R.string.dialog_ok))
                .setCancelClickListener(onCancelClickListener)
                .setConfirmClickListener(onOkClickListener)
                .showCancelButton(isShowCancelButton);
        sweetAlertDialog.setCanceledOnTouchOutside(false);
        sweetAlertDialog.show();
        return sweetAlertDialog;
    }

    public SweetAlertDialog showAlert(int type, String title, String content, String okText, SweetAlertDialog.OnSweetClickListener onOkClickListener,
                                      String cancelText, SweetAlertDialog.OnSweetClickListener onCancelClickListener, boolean isShowCancelButton, boolean isShowCloseButton
            , boolean isCanceledOnTouchOutside) {
        SweetAlertDialog sweetAlertDialog = new SweetAlertDialog(this, type)
                .setTitleText(title != null ? title : getString(R.string.dialog_default_title))
                .setContentText(content)
                .setCancelText(isShowCancelButton ? cancelText != null ? cancelText : getString(R.string.dialog_cancel) : null)
                .setConfirmText(okText != null ? okText : getString(R.string.dialog_ok))
                .setCancelClickListener(onCancelClickListener)
                .setConfirmClickListener(onOkClickListener)
                .showCancelButton(isShowCancelButton)
                .showCloseButton(isShowCloseButton);
        sweetAlertDialog.setCanceledOnTouchOutside(isCanceledOnTouchOutside);
        sweetAlertDialog.show();
        return sweetAlertDialog;
    }

    public void showGuide(int layout, View highLightView, HighLight.Shape shape, String tag, boolean isShowAlways) {
        try {
            Animation enterAnimation = new AlphaAnimation(0f, 1f);
            enterAnimation.setDuration(200);
            enterAnimation.setFillAfter(true);

            Animation exitAnimation = new AlphaAnimation(1f, 0f);
            exitAnimation.setDuration(200);
            exitAnimation.setFillAfter(true);

            NewbieGuide.with(this)
                    .setLabel(tag)
                    .alwaysShow(isShowAlways)
                    .addGuidePage(GuidePage.newInstance().setEverywhereCancelable(true).setEnterAnimation(enterAnimation).setExitAnimation(exitAnimation)
                            .setBackgroundColor(getResources().getColor(R.color.colorGuideBg))
                            .addHighLight(highLightView, shape, SZUtil.dip2px(5), 0, null)
                            .setLayoutRes(layout))
                    .show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void showGuideList(List<Integer> layoutList, List<View> highLightViewList, List<HighLight.Shape> shapeList, String tag, boolean isShowAlways) {
        try {
            Builder builder = NewbieGuide.with(this)
                    .setLabel(tag)
                    .alwaysShow(isShowAlways);
            for (int i = 0; i < layoutList.size(); i++) {
                GuidePage guidePage = GuidePage.newInstance().setEverywhereCancelable(true);
                guidePage.addHighLight(highLightViewList.get(i), shapeList.get(i), SZUtil.dip2px(5), 0, null);
                guidePage.setLayoutRes(layoutList.get(i));

                Animation enterAnimation = new AlphaAnimation(0f, 1f);
                enterAnimation.setDuration(200);
                enterAnimation.setFillAfter(true);

                Animation exitAnimation = new AlphaAnimation(1f, 0f);
                exitAnimation.setDuration(200);
                exitAnimation.setFillAfter(true);

                guidePage.setEnterAnimation(enterAnimation);//进入动画
                guidePage.setExitAnimation(exitAnimation);//退出动画

                guidePage.setBackgroundColor(getResources().getColor(R.color.colorGuideBg));
                builder.addGuidePage(guidePage);
            }
            builder.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void showRelativeGuide(RelativeGuide relativeGuide, View highLightView, HighLight.Shape shape, String tag, boolean isShowAlways) {
        try {
            Animation enterAnimation = new AlphaAnimation(0f, 1f);
            enterAnimation.setDuration(200);
            enterAnimation.setFillAfter(true);

            Animation exitAnimation = new AlphaAnimation(1f, 0f);
            exitAnimation.setDuration(200);
            exitAnimation.setFillAfter(true);

            NewbieGuide.with(this)
                    .setLabel(tag)
                    .alwaysShow(isShowAlways)
                    .addGuidePage(GuidePage.newInstance().setEverywhereCancelable(true).setEnterAnimation(enterAnimation).setExitAnimation(exitAnimation)
                            .setBackgroundColor(getResources().getColor(R.color.colorGuideBg))
                            .addHighLight(highLightView, shape, SZUtil.dip2px(5), 0, relativeGuide))
                    .show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void showRelativeGuideList(List<RelativeGuide> relativeGuideList, List<View> highLightViewList, List<HighLight.Shape> shapeList, String tag, boolean isShowAlways) {
        try {
            Builder builder = NewbieGuide.with(this)
                    .setLabel(tag)
                    .alwaysShow(isShowAlways);
            for (int i = 0; i < relativeGuideList.size(); i++) {
                GuidePage guidePage = GuidePage.newInstance().setEverywhereCancelable(true);
                guidePage.addHighLight(highLightViewList.get(i), shapeList.get(i), SZUtil.dip2px(5), 0, relativeGuideList.get(i));

                Animation enterAnimation = new AlphaAnimation(0f, 1f);
                enterAnimation.setDuration(200);
                enterAnimation.setFillAfter(true);

                Animation exitAnimation = new AlphaAnimation(1f, 0f);
                exitAnimation.setDuration(200);
                exitAnimation.setFillAfter(true);

                guidePage.setEnterAnimation(enterAnimation);//进入动画
                guidePage.setExitAnimation(exitAnimation);//退出动画

                guidePage.setBackgroundColor(getResources().getColor(R.color.colorGuideBg));
                builder.addGuidePage(guidePage);
            }
            builder.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void loadImg(ImageView imageView, String url) {
        if (imageView != null) {
            SZGlide.load(this, url, imageView);
        }
    }

    public void loadImg(ImageView imageView, String url, int placeholder) {
        if (imageView != null) {
            SZGlide.load(this, url, imageView, placeholder);
        }
    }

    public boolean hasFileManagePower() {
        return SZUtil.hasFileManagePower();
    }

    public void finishAndRemoveActivity() {
        SZApp.getInstance().removeActivity(this);
        finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!hasFragment()) {
            SZManager.getInstance().onUMPageStart(getRequestTag());
        }
        SZManager.getInstance().onUMResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (!hasFragment()) {
            SZManager.getInstance().onUMPageEnd(getRequestTag());
        }
        SZManager.getInstance().onUMPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cancelByTag(getRequestTag());
        SZApp.getInstance().removeActivity(this);
        if (isRegist) {
            try {
                EventBus.getDefault().unregister(this);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void registEventBus() {
        try {
            if (!isRegist) {
                EventBus.getDefault().register(this);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        isRegist = true;
    }

    public boolean isDealOnReloadData(List list) {
        if (SZValidatorUtil.isValidList(list)) {
            if (list.size() <= SZConst.LIMIT_MAX) {
                return false;
            }
        }
        onReloadData(false);
        return true;
    }

    public boolean isShowTitleInit() {
        return true;
    }

    public boolean isShowDarkTitleText() {
        return false;
    }

    private boolean isNeedLogin = false;

    public boolean isNeedLogin() {
        return isNeedLogin;
    }

    public void setNeedLogin(boolean needLogin) {
        isNeedLogin = needLogin;
    }

    public boolean hasFragment() {
        return false;
    }

    public boolean isTransparentStatus() {
        return isTransparentStatus;
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
//        super.onSaveInstanceState(outState, outPersistentState);
    }

    @SuppressLint("MissingSuperCall")
    @Override
    protected void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);
    }
}
